#pragma once

#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

namespace client
{
    class TcpClient
    {
        public:
        TcpClient(const std::string &serverip, const uint16_t &serverport)
        : _sock(-1), _serverip(serverip), _port(serverport)
        {}
        void initClient()
        {
            // 1. 创建socket套接字
            _sock = socket(AF_INET, SOCK_STREAM, 0);
            if(_sock < 0)
            {
                std::cerr << "socket create error" << std::endl;
                exit(2);
            }
            // 2. 客户端需要bind, 但是OS自动bind, 不需要显示的bind
            // 3. 不需要listen, 因为我们是一对多的那个多, 为我们服务的只有一台服务器
            // 4. 也不需要accept!
            // 5. 而是要向服务器发起连接!
        }
        void start()
        {
            struct sockaddr_in server;
            memset(&server, 0, sizeof(server));
            server.sin_family = AF_INET;
            server.sin_port = htons(_port);
            server.sin_addr.s_addr = inet_addr(_serverip.c_str());

            if(connect(_sock, (struct sockaddr*)&server, sizeof(server)) != 0)
            {
                std::cerr << "socket connect error" << std::endl;
            }
            else
            {
                std::string msg;
                while(true)
                {
                    std::cout << "Enter# ";
                    std::getline(std::cin, msg);
                    write(_sock, msg.c_str(), msg.size());

                    char buffer[1024];
                    int n = read(_sock, buffer, sizeof(buffer));
                    if(n > 0)
                    {
                        buffer[n] = 0;
                        std::cout << "Server回显# " << buffer << std::endl;
                    }
                    else
                    {
                        break;
                    }
                }
            }
        }
        ~TcpClient()
        {
            if(_sock >= 0) close(_sock);
        }
        private:
        int _sock;
        std::string _serverip;
        uint16_t _port;
    };
}